# encoding: utf-8
import logging


import jwt
from django.http import JsonResponse

from utils import code_config



def base_code(data, code=code_config.CODE_0):
    """
    定义接口数据返回格式
    :param code: 错误码定义 {'code': 0, 'msg': 'success.'}
    :param data: 返回数据，字典类型
    :return: {'code': 0, 'msg': 'success.', 'data': {}}
    """
    r_code = {'data': data}
    r_code.update(**code)
    return r_code


def encryption(data, signature, secret_key):
    """加密"""
    dic = {
        'iss': signature,  # 签名
        'data': data
    }
    s = jwt.encode(dic, secret_key, algorithm='HS256')  # 加密生成字符串
    return s.decode('utf-8')


def decryption(value, signature, secret_key):
    """解密"""
    try:
        data = jwt.decode(value, secret_key, issuer=signature, algorithms=['HS256'])  # 解密，校验签名
    except Exception as e:
        data = None
    return data


def resp_decorator(func):

    def wrapper(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:

            code_config.CODE_406["msg"]=str(e)
            return JsonResponse(code_config.CODE_406)
    return wrapper




